package com.Cychat.auth.service.Impl;

import com.Cychat.auth.service.ALiYunOssSevice;
import com.Cychat.commons.config.OssConfig;
import com.aliyun.oss.OSS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * Auther: 刘博文  <br/>
 * Date: 2025/10/31:14:05  <br/>
 * Description: 文件上传service实现类
 */
@Service
public class ALiYunOssSeviceImpl implements ALiYunOssSevice {
private static final Logger log = LoggerFactory.getLogger(ALiYunOssSeviceImpl.class);
    @Autowired
    private OSS ossClient;

    @Autowired
    private OssConfig ossConfig;

    @Override
    public String updateAvatar(MultipartFile file, Long userId) throws IOException {
        try {
            // 指定文件夹路径，例如: avatars/用户ID/文件名
            String folderPath = "avatars/" + userId + "/";

            // 生成唯一文件名
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();

            // 完整的对象键（包含文件夹路径）
            String objectName = folderPath + fileName;

            // 上传文件
            ossClient.putObject(ossConfig.getBucketName(), objectName, file.getInputStream());

            // 返回访问URL
            return "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint() + "/" + objectName;
        }catch (IOException e) {
            log.error("头像上传过程中发生IO异常", e);
            throw new RuntimeException("头像上传失败", e);
        } catch (Exception e) {
            log.error("头像上传过程中发生未知异常", e);
            throw new RuntimeException("头像上传失败", e);
        } finally {
            // 注意：这里不再关闭ossClient，因为它现在是Spring管理的Bean
        }
    }
}
